package bos.service.impl;

import javax.annotation.Resource;

import org.activiti.engine.IdentityService;
import org.activiti.engine.impl.persistence.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import bos.dao.IRoleDao;
import bos.dao.IUserDao;
import bos.domain.Role;
import bos.domain.User;
import bos.service.IUserService;
import bos.utils.MD5Utils;
import bos.utils.PageBean;

@Service
@Transactional
public class UserServiceImpl implements IUserService{
	@Autowired
	private IUserDao userDao;
	@Resource
	private IdentityService identityService;
	@Resource
	private IRoleDao roleDao;
	@Override
	public User login(User user) {
		String username=user.getUsername();
		String password=user.getPassword();
		password = MD5Utils.md5(password);
		
		return userDao.findByUsernameAndPassword(username,password);
	}

	@Override
	public void editPassword(String password, String id) {
		userDao.executeUpdate("editPassword",password,id);
	}

	@Override
	public void pageQuery(PageBean pageBean) {
			userDao.pageQuery(pageBean);
	}

	@Override
	public void save(User user, String[] roleIds) {
		String password=user.getPassword();
		password=MD5Utils.md5(password);
		user.setPassword(password);
		userDao.save(user);
		
		org.activiti.engine.identity.User actuser=new UserEntity(user.getId());
		identityService.saveUser(actuser);
		
		for(String roleId : roleIds){
			Role role=roleDao.findById(roleId);
			
			user.getRoles().add(role);
			
			identityService.createMembership(actuser.getId(), role.getName());
			
		}
	}
}
